/**
 * Copyright 2010 Butin Kirill <kiryaka@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flexupload.manager
{
	import flash.net.FileReference;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import mx.rpc.events.ResultEvent;
	
	import org.flexupload.Flexupload;
	import org.flexupload.model.ServerReply;
	import org.flexupload.remote.FlexuploadService;
	import org.flexupload.status.UploadStatus;
	import org.flexupload.strategy.DevStrategy;

	public class UploadManager
	{
		private var fileManager:FileManager;
		private var strategy:DevStrategy;
		private var uploadStatus:UploadStatus;		
		private var mainHandlerIntervalId:uint;
		public function UploadManager(){}
		public function setFileManager(fileManager:FileManager):void{
			this.fileManager = fileManager;
		}
		public function setStrategy(strategy:DevStrategy):void{
			this.strategy = strategy;
		}
		
		public function setUploadStatus(uploadStatus:UploadStatus):void{
			this.uploadStatus = uploadStatus;
		}		
		
		public function mainHandler():void{
			if ( fileManager.hasFileForUpload() && strategy.canStartNewFile()){
				var file:FileReference = fileManager.getFileForUpload();
				strategy.startUploadFile(file);				
			}
			if (strategy.getActiveFilesCount() == 0 && uploadStatus.getTotalBytes() == uploadStatus.getBytesTransfered()){
				clearInterval(mainHandlerIntervalId);
				var service:FlexuploadService = strategy.getControlService();
				service.addEventListener(ResultEvent.RESULT, finishSessionHandler);
				service.finishSession();
			}			
		}
		private function finishSessionHandler(event:ResultEvent):void{
			var serverReply:ServerReply = ServerReply(event.result);
			if (serverReply.status != ServerReply.SUCCESS ||
				serverReply.type != ServerReply.TYPE_FINISH_SESSION
			){
				return;
			}
			FlexuploadService(event.target).removeEventListener(ResultEvent.RESULT, finishSessionHandler);
			Flexupload.getInstance().finish();			
		}
		public function start():void{
			fileManager.start();
			mainHandlerIntervalId = setInterval(mainHandler, 500);	
		}
		public function finish():void{
			clearInterval(mainHandlerIntervalId);
			fileManager.finish();
		}
	}
}